//
//  商户HomeCtr.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/10/16.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import soapp
import Eelay


extension SellerHomeCtr{
    public class EmptyCell: JoTableCell {
        let infoL = UILabel()
        override public func addLayoutRules() {
            contentView.eelay = [
                [infoL,[ee.T.L.R,[30,40,-40]]]
            ]
            infoL.ui.center.font15.cl_888.text("没有相关商品".loc)
        }
        
        override public func mo_model_reload() {
            infoL.text = mo.model["message","没有相关商品".loc]
        }
    }
}

open class SellerHomeCtr: NavChangeTableContainer{
    open override var sections: TP.section{
        get{
            let sec:TP.section = [
                [],
                [],
                ]
            return sec
        }
    }
    open override var selector: TP.selector{
        get{
            let sel = [
                "<default>":Goods.TowGoodsCel.self,
                "<\(page_load_section)>":Goods.TowGoodsCel.self,
                "cellID<empty>":EmptyCell.self,
                ]
            return sel
        }
    }
    
    var goodsFilter:GoodsFilter = GoodsFilter()
    
    var baseParams:[String:Any]{
        get{
            let params = ["id":sellerID]
            return params
        }
    }
    
    required public init() {
        super.init()
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override open func mo_model_reload() {
        //外部拿到的数据时构造符合baseParams 参数的model
        if mo.model["fromp","XX"] == "XX"
        {
            mo.model["fromp"] = mo.model["plat_id"]
        }
    }
    
    var sellerID:String{
        get{
            var seller_id = ""
            let out_link = mo.model["outlink_href",""]
            if out_link.len > 1{
                //                let paramas = AppLink.params(str: out_link).mutable_dictionary
                //                if seller_id.len < 1{
                //                    seller_id = paramas["id",""]
                //                }
            }
            if seller_id.len < 1{
                seller_id = mo.model["id","1"]
            }
            return "31"
        }
    }
    public var orderBar = OrderMenu()
    override open func viewDidLoad() {
        
        self.page_load_section = "section0"
        self.content = TermsContainer.table(
            title: mo.model["name","商品列表".loc],
            emptyMsg:"",
            net: JoTask().get.url(_SURL.商品列表.url),
            params:baseParams,
            node: "list",
            cellType: Goods.TowGoodsCel.self,
            cellHeigth: nil,
            detailType: nil,
            test: true
        )
        
        super.viewDidLoad()
        self.paginator.type = .bottom
        orderBar.delegate = self
        tableView.backgroundColor = .white
        //        tableView.buildDynamicHeight(height: 260)
        tableView.estimatedRowHeight = 0
        tableView.rowHeight = Goods.row_height
        load(sections: sections, selector: selector)
        
        //        if #available(iOS 11.0, *) {
        //            tableView.contentInsetAdjustmentBehavior = .never
        //        } else {
        //            self.automaticallyAdjustsScrollViewInsets = false;
        //            // Fallback on earlier versions
        //        }
        var testNum = 0
        
        paginator.item_creater = {() in
            var one = [String:Any]()
            one["cover"] = __goods.one_str
            one["name"] = __goodsNames.one_str
            one["price"] = "\(100+testNum)"
            testNum += 1
            return one.mutable_dictionary
        }
        
        title = "品牌".loc
        //        tableView.contentInset = [0,0,0,0]
        //        reload_page()
        
        mo_request_send()
        buildBackBtChangeNavSupport()
        tableView.backgroundColor = UIColor.table_bg_color
    }
    
    
    lazy var hud:HUD = {
        return HUD(at: self.view)
    }()
    
    open override func reload_page() {
        switch appearStatus {
        case .didAppear:
            hud.show().mode(.indeterminate)
        default:
            break
        }
        
        //        weak var wself = self
        //        co_delay(delay: 1.2) {
        //            wself?.loadMore(page: PageConfig.page_begin)
        //        }
        loadMore(page: PageConfig.page_begin)//            refresh()
    }
    
    override open func mo_request_send() {
        
        weak var wself = self
        //        loadingV.loading()
        //        JoTask().get.log.log_response().params(["id":sellerID])._url(.品牌页面).json_handle { (success, msg, obj, resp) in
        //            wself?.loadingV.dismiss()
        //            if success{
        //                if let dict = obj as? NSMutableDictionary{
        wself?.mo.detail = NSMutableDictionary()
        //                    return
        //                }
        //            }
        //            wself?.loadingV.show(message: msg, title: "")
        //        }.run()
    }
    
    override open func mo_detail_reload() {
        let header =  SellerHeader(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: (245.co-TP.topHeight)))
        header.mo.controller = self
        navChangeOffsetY = 245.co-(2.0 * TP.topHeight)
        self.tableView.tableHeaderView  = header
        reload_page()
        
    }
    
    
    override open func loadOnePage(list: [Any]) -> [Any] {
        var new_list = [AnyObject]()
        for (index,one) in list.enumerated()
        {
            if index%2 == 0
            {
                let dict = NSMutableDictionary()
                dict["options"] = [one].mutable_array
                new_list.append(dict)
            }
            else{
                if let dict = new_list.last as? NSMutableDictionary{
                    if let list = dict["options"] as? NSMutableArray
                    {
                        list.add(one)
                    }
                }
            }
        }
        return new_list
    }
    
    
    
    override open func load(page: Int, succeed: Bool, list: [Any], response: RootData?, status : PageDataStatus, scrollView: UIScrollView) {
        if page == paginator.page_begin
        {
            hud.hide(animated: true, delay: 0)
        }
        
        (self.backMsgView as? UILabel)?.ui.color(hex: "#fff0")
        super.load(page: page, succeed: succeed, list: list, response: response, status: status, scrollView: scrollView)
        switch status {
        case .err(_):
            "数据获取失败".loc.alert()
        case .empty:
            if page == paginator.page_begin{
                tableView.model <-- ("section1",[["cellID":"empty","message":"没有相关商品".loc]].mutable_array,NodeInsert.arrayRefresh)
                tableView.reloadSections(IndexSet(integer:1), with: .none)
            }
        //            tableView.reloadData()
        default:
            tableView.model <-- ("section1",NSMutableArray(),NodeInsert.arrayRefresh)
            tableView.reloadData()
        }
        
    }
    
    override open func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 40
        default:
            return 0
        }
    }
    override open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0
        {
            return self.orderBar
        }
        return nil
    }
    
    
    
    override open func scrollViewDidScroll(_ scrollView: UIScrollView) {
        super.scrollViewDidScroll(scrollView)
        if self.appearStatus != .didAppear
        {
            return
        }
        if let headerView = self.tableView.tableHeaderView as? SellerHeader
        {
            headerView.scrollViewDidScroll(scrollView: scrollView)
        }
        
    }
    
}

extension SellerHomeCtr:OrderMenuDelegate
{
    func reloadGoods(with params:[String:Any]) {
        //        print("=====kkk---===|\(params)")
        let all_params = params + self.baseParams + self.goodsFilter.values
        self.paginator.parameters = all_params
        reload_page()
        
    }
    
    func changeTheOrder(params: [String : Any]) {
        reloadGoods(with: params)
    }
    
    func changeTheFilter(params: [String : Any]) {
        
        reloadGoods(with: params)
    }
    
}

